package eclipse.weibo.modle;

import java.net.URL;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

import weibo4j.Comment;
import weibo4j.Status;
import weibo4j.User;
import eclipse.weibo.util.ReadImageUtil;

public class ReadWeiboCommentImageThread extends Thread {
    private Table table;
    private Display display;
    private URL[] urls;

    public ReadWeiboCommentImageThread(Table table, URL[] urls, Display display) {
        this.table = table;
        this.display = display;
        this.urls = urls;
    }

    public void run() {
        for (URL url : this.urls) {
            ReadImageUtil.read(url);
        }

        this.display.asyncExec(new TThread());
    }

    class TThread extends Thread {
        public void run() {
            TableItem[] tis = ReadWeiboCommentImageThread.this.table.getItems();
            for (TableItem ti : tis) {
                try {
                    Object d = ti.getData();
                    URL url = null;
                    ImageData id;
                    if (d instanceof Status) {
                        Status s = (Status) d;
                        url = s.getUser().getProfileImageURL();
                        id = ReadImageUtil.read(url);
                        ti.setImage(0, new Image(ti.getDisplay(), id));
                        ti.setText(0, "");
                        continue;
                    }
                    if (d instanceof Comment) {
                        Comment c = (Comment) d;
                        url = c.getUser().getProfileImageURL();
                        id = ReadImageUtil.read(url);
                        id = id.scaledTo(25, 25);
                        ti.setImage(0, new Image(ti.getDisplay(), id));
                        ti.setText(0, "");
                        continue;
                    }
                    if (d instanceof User) {
                        User c = (User) d;
                        url = c.getProfileImageURL();
                        id = ReadImageUtil.read(url);

                        ti.setImage(0, new Image(ti.getDisplay(), id));
                        ti.setText(0, "");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
